// 导入存储服务和灯光模式服务
const storageService = require('../../../services/storage')
// 导入防抖函数
const {
  debounce,
  throttle
} = require('../../../utils/debounce.js')


const lightCommonService = require('../../../services/light_common_service')
const shortcutModeService = require('../../../services/shortcut_mode_service')
const playerModeService = require('../../../services/player_mode_service')
const advancedModeService = require('../../../services/advanced_mode_service')

const channelNum = 8
const modeNum = 3
const appInstance = getApp();

Page({
  data: {
    currentIndex: 0,
    showTimerPopup: false,
    timerTasks: [],
    modeOptions: [], // Dynamically loaded from modeImages
    //allModes: [], // 所有模式列表，包括快捷模式和玩家模式
    /*brightnessOptions: Array.from({
      length: 100
    }, (_, i) => i + 1),*/
    showDeleteConfirm: false,
    deleteTaskIndex: -1,
    showTimeConflictConfirm: false, // 时间冲突提醒弹窗
    showCrossZeroConfirm: false, // 跨0点确认弹窗
    crossZeroModeEnabled: false, // 跨0点模式开关状态
    timeConflictMessage: '', // 时间冲突错误消息
    showFirstVisitTip: false, // 首次访问提示弹窗
    isManualMode: false, // 手动模式状态
    // 模式图片和名称数据
    modeImages: [{
        image: 'https://img.99666666.xyz/yugang/images/sps.webp',
        name: 'SPS模式'
      },
      {
        image: 'https://img.99666666.xyz/yugang/images/lps.webp',
        name: 'LPS模式'
      },
      {
        image: 'https://img.99666666.xyz/yugang/images/slps.webp',
        name: 'SPS\\LPS混养'
      }
    ],
    // 每个模式的亮度设置，初始值为0（范围0-10）
    modeSettings: [{
        brightness: 0
      },
      {
        brightness: 0
      },
      {
        brightness: 0
      }
    ],

    did: null,
    device: null,
    switchType: 0, //1=手动切自动(废弃)；2=自动切手动；3=启用行程；4=禁用行程；5=禁用行程切手动
    tmpIndex: -1,
    tmpEnabled: false,
    mattData: null,

    isGroup: false,
    devices: [],
    syncNum: 0,
  },

  // 批量更新数据，避免多次调用setData
  batchUpdate(data, callback) {
    if (this.batchData === undefined) {
      this.batchData = {}
    }

    // 合并需要更新的数据
    Object.assign(this.batchData, data)

    // 使用nextTick确保在一个渲染周期内只调用一次setData
    wx.nextTick(() => {
      if (Object.keys(this.batchData).length > 0) {
        this.setData(this.batchData, callback)
        this.batchData = {}
      }
    })
  },

  // 获取默认模式设置
  getDefaultModeSettings: function () {
    return [{
        brightness: 0
      },
      {
        brightness: 0
      },
      {
        brightness: 0
      }
    ]
  },

  // 初始化模式设置并发送亮度信号
  initModeSettings: function (index) {
    const defaultModeSettings = this.getDefaultModeSettings()
    // 初始化最后发送的模式和亮度记录，避免undefined比较
    if (this.lastSentMode === undefined) this.lastSentMode = -1
    if (this.lastSentBrightness === undefined) this.lastSentBrightness = -1

    // 更新图片样式，确保UI显示正确
    this.updateImageClasses(index)

    // 合并多个设置为一个setData调用
    this.batchUpdate({
      modeSettings: defaultModeSettings,
      currentIndex: index, // 确保当前索引与初始化的模式一致
    }, () => {
      // 在设置完默认值后，使用默认亮度发送信号
      // 添加安全检查，确保索引有效且对应的设置存在
      if (
        defaultModeSettings &&
        defaultModeSettings[index] &&
        defaultModeSettings[index].brightness !== undefined
      ) {
        const defaultBrightness = defaultModeSettings[index].brightness
        this.sendBrightnessToDevice(index, defaultBrightness)
      } else {
        console.warn(`initModeSettings: 无法获取模式${index}的默认亮度设置`)
        // 使用安全的默认值
        this.sendBrightnessToDevice(index, 0) // 使用0作为默认亮度
      }
    })
  },

  onLoad: function (options) {
    // 初始化防抖的亮度调整函数
    this.debouncedSendBrightness = debounce((index, brightness) => {
      this.sendBrightnessToDevice(index, brightness)
    }, 200)

    // 使用节流函数处理模式切换
    this.throttledModeChange = throttle((index) => {
      this.handleModeChange(index)
    }, 300)

    console.log(options);
    this.setData({
      did: options.did
    });

    let isGroup = false
    let dobj = storageService.getDeviceInfo(options.did)
    this.data.device = dobj
    if (dobj.deviceId.startsWith('group_')) {
      isGroup = true
      const devices = storageService.batchGetDeviceInfo(dobj.deviceIds)
      this.data.devices = [...devices]
    }

    const entityId = options.did
    const deviceType = this.data.device.deviceType

    try {
      // Populate modeOptions from modeImages
      const modeOptions = []

      const smodeOptions = shortcutModeService.getModeNames(this.data.device.deviceType)
      const pmodeOptions = playerModeService.getModeNames(entityId)
      modeOptions.push(...smodeOptions)
      modeOptions.push(...pmodeOptions)
      // 使用确定的 deviceType 调用
      const lightModeState = storageService.getLightModeState(entityId)
      const isManual = lightModeState === 'manual'

      // 总是获取快捷模式数据
      let shortcutModeData = storageService.getShortcutModeData(entityId, isGroup, deviceType)
      let currentIndex = shortcutModeData.currentIndex
      if (shortcutModeData.modeSettings == null) {
        shortcutModeData.modeSettings = this.getDefaultModeSettings()
      }

      // 检查是否是首次访问 - 从临时变量获取 deviceType
      if (shortcutModeData.isFirstVisit) {
        // 设置已访问标记 - 从临时变量获取 deviceType
        storageService.setShortcutModeVisited(entityId, isGroup, deviceType)
      }

      console.log(`shortcutModeData:${JSON.stringify(shortcutModeData)}`)
      // 合并所有的 setData 调用
      this.setData({
        modeOptions: modeOptions, // 设置 modeOptions
        //allModes: allModes, // 设置 allModes
        isManualMode: isManual, // 设置 isManualMode
        currentIndex: currentIndex, // 使用上面已验证的currentIndex
        modeSettings: shortcutModeData.modeSettings, // 使用上面已验证的modeSettings
        timerTasks: shortcutModeData?.timerTasks || [], // 使用已获取的shortcutModeData，默认空数组
        showFirstVisitTip: shortcutModeData.isFirstVisit, // 设置 showFirstVisitTip
        isGroup: isGroup
      })
    } catch (error) {
      console.error('初始化页面错误:', error)
    }
  },

  onReady: function () {
    const $t = this;
    if (!this.data.isGroup) {
      wx.$event.on(this.data.device.topicSub, this, (obj) => {
        if (obj.type == "chgAutoRun") {
          $t.switchChangeResult(1);
        } else if (obj.type == "syncDataUp") {
          $t.handleSyncToDeviceDialogResult(1);
        }
      })
    } else {
      this.data.devices.forEach(device => {
        wx.$event.on(device.topicSub, $t, (obj) => {
          if (obj.type == "chgAutoRun") {
            $t.switchChangeResultGroup(1);
          } else if (obj.type == "syncDataUp") {
            $t.handleSyncToDeviceDialogResultGroup(1);
          }
        })
      })
    }
  },
  onShow: function () {
    this.updateImageClasses(this.data.currentIndex)
    const index = this.data.currentIndex
    const brightness = this.data.modeSettings[index].brightness
    this.sendBrightnessToDevice(index, brightness)
  },

  // 轮播图切换事件
  onSwiperChange: function (e) {
    const current = e.detail.current
    this.setData({
      currentIndex: current,
    })
    this.updateImageClasses(current)

    // 确保lastSentMode和lastSentBrightness已初始化
    if (this.lastSentMode === undefined) this.lastSentMode = -1
    if (this.lastSentBrightness === undefined) this.lastSentBrightness = -1
    const brightness = this.data.modeSettings[current].brightness
    // 检查是否与上次发送的模式和亮度相同，避免重复发送
    if (this.lastSentMode !== current || this.lastSentBrightness !== brightness) {
      this.sendBrightnessToDevice(current, brightness)
    }
  },

  updateImageClasses: function (currentIndex) {
    const modeImages = this.data.modeImages.map((item, index) => {
      if (index === currentIndex) {
        item.class = 'mode-image active'
      } else if (index === currentIndex - 1 || index === currentIndex + 6) {
        item.class = 'mode-image left'
      } else if (index === currentIndex + 1 || index === currentIndex - 6) {
        item.class = 'mode-image right'
      } else {
        item.class = 'mode-image'
      }
      return item
    })
    this.setData({
      modeImages: modeImages,
    })
  },

  // 点击指示点切换模式
  switchToMode: function (e) {
    const index = e.currentTarget.dataset.index
    this.setData({
      currentIndex: index,
    })

    // 更新图片样式
    this.updateImageClasses(index)

    // 确保lastSentMode和lastSentBrightness已初始化
    if (this.lastSentMode === undefined) this.lastSentMode = -1
    if (this.lastSentBrightness === undefined) this.lastSentBrightness = -1

    const brightness = this.data.modeSettings[index].brightness

    // 检查是否与上次发送的模式和亮度相同，避免重复发送
    if (this.lastSentMode !== index || this.lastSentBrightness !== brightness) {
      this.sendBrightnessToDevice(index, brightness)
    }
  },

  // 滑块触摸开始事件
  sliderTouchStart: function (e) {
    if (!this.data.isManualMode) {
      wx.showModal({
        title: '提示',
        content: '行程模式，无法操作。',
        showCancel: false,
      })
      return
    }
    this.startX = e.touches[0].clientX
    this.sliderLeft = e.currentTarget.offsetLeft
    this.sliderWidth = e.currentTarget.offsetWidth
  },

  // 滑块触摸移动事件
  sliderTouchMove: function (e) {
    if (!this.data.isManualMode) {
      return
    }
    const moveX = e.touches[0].clientX
    const diffX = moveX - this.startX

    // 计算滑块位置百分比
    let sliderRect = wx.createSelectorQuery().select('.custom-slider').boundingClientRect()
    sliderRect.exec(res => {
      if (!res || !res[0]) return

      const sliderWidth = res[0].width
      const offsetX = e.touches[0].clientX - res[0].left
      let percentage = offsetX / sliderWidth

      // 限制百分比在0-1之间
      percentage = Math.max(0, Math.min(1, percentage))

      // 计算亮度值（0-10档位）
      // 使用Math.ceil确保最小值为0，最大值为10
      const brightness = Math.min(10, Math.max(0, Math.floor(percentage * 11)))

      // 更新当前模式的亮度值
      const index = this.data.currentIndex

      // 确保当前索引的数据存在
      const modeSettings = [...this.data.modeSettings] // 创建副本避免直接修改

      // 如果当前索引的数据不存在或亮度值无效，初始化它
      if (!modeSettings[index] || modeSettings[index].brightness === undefined) {
        modeSettings[index] = {
          brightness: brightness
        }
      } else {
        modeSettings[index].brightness = brightness
      }

      this.setData({
        modeSettings: modeSettings,
      })
    })
  },

  // 滑块触摸结束事件
  sliderTouchEnd: function (e) {
    if (!this.data.isManualMode) {
      return
    }
    const index = this.data.currentIndex

    const brightness = this.data.modeSettings[index].brightness

    // 确保lastSentMode和lastSentBrightness已初始化
    if (this.lastSentMode === undefined) this.lastSentMode = -1
    if (this.lastSentBrightness === undefined) this.lastSentBrightness = -1

    // 检查是否与上次发送的模式和亮度相同，避免重复发送
    if (this.lastSentMode !== index || this.lastSentBrightness !== brightness) {
      // 发送亮度设置到设备
      this.sendBrightnessToDevice(index, brightness)
    }
  },

  // 通过MQTT发送亮度设置到设备的函数
  sendBrightnessToDevice: function (modeIndex, brightness) {
    // 记录最后发送的模式和亮度，用于避免重复发送
    this.lastSentMode = modeIndex
    this.lastSentBrightness = brightness

    // 定义MQTT消息对象
    let mqttMessage = {}

    // 根据模式索引处理不同的模式
    if (modeIndex === 0) {
      // SPS模式的索引为0
      // 根据亮度档位0-10设置所有通道的空占比
      let rDuty = 0,
        gDuty = 0,
        bDuty = 0,
        wDuty = 0,
        lbDuty = 0,
        rbDuty = 0,
        pDuty = 0,
        uvDuty = 0

      // 根据表格设置对应的空占比值
      switch (brightness) {
        case 0:
          rDuty = 0
          gDuty = 0
          bDuty = 0
          wDuty = 0
          lbDuty = 0
          rbDuty = 0
          pDuty = 0
          uvDuty = 0
          break
        case 1:
          rDuty = 17
          gDuty = 11
          bDuty = 102
          wDuty = 52
          lbDuty = 72
          rbDuty = 102
          pDuty = 92
          uvDuty = 92
          break
        case 2:
          rDuty = 34
          gDuty = 21
          bDuty = 205
          wDuty = 103
          lbDuty = 143
          rbDuty = 205
          pDuty = 184
          uvDuty = 184
          break
        case 3:
          rDuty = 51
          gDuty = 32
          bDuty = 307
          wDuty = 155
          lbDuty = 215
          rbDuty = 307
          pDuty = 276
          uvDuty = 276
          break
        case 4:
          rDuty = 68
          gDuty = 42
          bDuty = 409
          wDuty = 206
          lbDuty = 286
          rbDuty = 409
          pDuty = 368
          uvDuty = 368
          break
        case 5:
          rDuty = 85
          gDuty = 53
          bDuty = 512
          wDuty = 258
          lbDuty = 358
          rbDuty = 512
          pDuty = 461
          uvDuty = 460
          break
        case 6:
          rDuty = 102
          gDuty = 63
          bDuty = 614
          wDuty = 309
          lbDuty = 430
          rbDuty = 614
          pDuty = 553
          uvDuty = 552
          break
        case 7:
          rDuty = 119
          gDuty = 74
          bDuty = 716
          wDuty = 361
          lbDuty = 501
          rbDuty = 716
          pDuty = 645
          uvDuty = 644
          break
        case 8:
          rDuty = 136
          gDuty = 84
          bDuty = 818
          wDuty = 412
          lbDuty = 573
          rbDuty = 818
          pDuty = 737
          uvDuty = 736
          break
        case 9:
          rDuty = 153
          gDuty = 95
          bDuty = 921
          wDuty = 464
          lbDuty = 644
          rbDuty = 921
          pDuty = 829
          uvDuty = 828
          break
        case 10:
          rDuty = 170
          gDuty = 105
          bDuty = 1023
          wDuty = 515
          lbDuty = 716
          rbDuty = 1023
          pDuty = 921
          uvDuty = 920
          break
        default:
          console.error('亮度档位超出范围:', brightness)
          return
      }

      // 构建SPS模式的MQTT消息
      mqttMessage = {
        mode: 'm0', // SPS模式对应m0
        gear: brightness, // 档位直接使用brightness值
        R: rDuty, // R通道空占比
        G: gDuty, // G通道空占比
        B: bDuty, // B通道空占比
        W: wDuty, // W通道空占比
        LB: lbDuty, // 浅蓝通道空占比
        RB: rbDuty, // 宝蓝通道空占比
        P: pDuty, // 紫光通道空占比
        UV: uvDuty // 紫外通道空占比
      }
    } else if (modeIndex === 1) {
      // LPS模式的索引为1
      // 根据亮度档位0-10设置所有通道的空占比
      let rDuty = 0,
        gDuty = 0,
        bDuty = 0,
        wDuty = 0,
        lbDuty = 0,
        rbDuty = 0,
        pDuty = 0,
        uvDuty = 0

      // 根据表格设置对应的空占比值
      switch (brightness) {
        case 0:
          rDuty = 0
          gDuty = 0
          bDuty = 0
          wDuty = 0
          lbDuty = 0
          rbDuty = 0
          pDuty = 0
          uvDuty = 0
          break
        case 1:
          rDuty = 34
          gDuty = 34
          bDuty = 68
          wDuty = 102
          lbDuty = 86
          rbDuty = 91
          pDuty = 80
          uvDuty = 34
          break
        case 2:
          rDuty = 68
          gDuty = 68
          bDuty = 136
          wDuty = 205
          lbDuty = 171
          rbDuty = 182
          pDuty = 159
          uvDuty = 68
          break
        case 3:
          rDuty = 102
          gDuty = 102
          bDuty = 205
          wDuty = 307
          lbDuty = 257
          rbDuty = 273
          pDuty = 239
          uvDuty = 102
          break
        case 4:
          rDuty = 136
          gDuty = 136
          bDuty = 273
          wDuty = 409
          lbDuty = 342
          rbDuty = 364
          pDuty = 318
          uvDuty = 136
          break
        case 5:
          rDuty = 171
          gDuty = 171
          bDuty = 341
          wDuty = 512
          lbDuty = 428
          rbDuty = 455
          pDuty = 398
          uvDuty = 171
          break
        case 6:
          rDuty = 205
          gDuty = 205
          bDuty = 409
          wDuty = 614
          lbDuty = 513
          rbDuty = 546
          pDuty = 477
          uvDuty = 205
          break
        case 7:
          rDuty = 239
          gDuty = 239
          bDuty = 477
          wDuty = 716
          lbDuty = 599
          rbDuty = 637
          pDuty = 557
          uvDuty = 239
          break
        case 8:
          rDuty = 273
          gDuty = 273
          bDuty = 546
          wDuty = 818
          lbDuty = 684
          rbDuty = 728
          pDuty = 636
          uvDuty = 273
          break
        case 9:
          rDuty = 307
          gDuty = 307
          bDuty = 614
          wDuty = 921
          lbDuty = 770
          rbDuty = 819
          pDuty = 716
          uvDuty = 307
          break
        case 10:
          rDuty = 341
          gDuty = 341
          bDuty = 682
          wDuty = 1023
          lbDuty = 855
          rbDuty = 910
          pDuty = 795
          uvDuty = 341
          break
        default:
          console.error('亮度档位超出范围:', brightness)
          return
      }

      // 构建LPS模式的MQTT消息
      mqttMessage = {
        mode: 'm1', // LPS模式对应m1
        gear: brightness, // 档位直接使用brightness值
        R: rDuty, // R通道空占比
        G: gDuty, // G通道空占比
        B: bDuty, // B通道空占比
        W: wDuty, // W通道空占比
        LB: lbDuty, // 浅蓝通道空占比
        RB: rbDuty, // 宝蓝通道空占比
        P: pDuty, // 紫光通道空占比
        UV: uvDuty // 紫外通道空占比
      }
    } else if (modeIndex === 2) {
      // SPS\LPS混养的索引为2
      // 根据亮度档位0-10设置所有通道的空占比
      let rDuty = 0,
        gDuty = 0,
        bDuty = 0,
        wDuty = 0,
        lbDuty = 0,
        rbDuty = 0,
        pDuty = 0,
        uvDuty = 0

      // 根据表格设置对应的空占比值
      switch (brightness) {
        case 0:
          rDuty = 0
          gDuty = 0
          bDuty = 0
          wDuty = 0
          lbDuty = 0
          rbDuty = 0
          pDuty = 0
          uvDuty = 0
          break
        case 1:
          rDuty = 34
          gDuty = 34
          bDuty = 102
          wDuty = 72
          lbDuty = 72
          rbDuty = 102
          pDuty = 82
          uvDuty = 72
          break
        case 2:
          rDuty = 68
          gDuty = 68
          bDuty = 205
          wDuty = 143
          lbDuty = 143
          rbDuty = 205
          pDuty = 164
          uvDuty = 143
          break
        case 3:
          rDuty = 102
          gDuty = 102
          bDuty = 307
          wDuty = 215
          lbDuty = 215
          rbDuty = 307
          pDuty = 245
          uvDuty = 215
          break
        case 4:
          rDuty = 136
          gDuty = 136
          bDuty = 409
          wDuty = 286
          lbDuty = 286
          rbDuty = 409
          pDuty = 327
          uvDuty = 286
          break
        case 5:
          rDuty = 171
          gDuty = 171
          bDuty = 512
          wDuty = 358
          lbDuty = 358
          rbDuty = 512
          pDuty = 409
          uvDuty = 358
          break
        case 6:
          rDuty = 205
          gDuty = 205
          bDuty = 614
          wDuty = 430
          lbDuty = 430
          rbDuty = 614
          pDuty = 491
          uvDuty = 430
          break
        case 7:
          rDuty = 239
          gDuty = 239
          bDuty = 716
          wDuty = 501
          lbDuty = 501
          rbDuty = 716
          pDuty = 573
          uvDuty = 501
          break
        case 8:
          rDuty = 273
          gDuty = 273
          bDuty = 818
          wDuty = 573
          lbDuty = 573
          rbDuty = 818
          pDuty = 654
          uvDuty = 573
          break
        case 9:
          rDuty = 307
          gDuty = 307
          bDuty = 921
          wDuty = 644
          lbDuty = 644
          rbDuty = 921
          pDuty = 736
          uvDuty = 644
          break
        case 10:
          rDuty = 341
          gDuty = 341
          bDuty = 1023
          wDuty = 716
          lbDuty = 716
          rbDuty = 1023
          pDuty = 818
          uvDuty = 716
          break
        default:
          console.error('亮度档位超出范围:', brightness)
          return
      }

      // 构建SPS\LPS混养模式的MQTT消息
      mqttMessage = {
        mode: 'm2', // SPS\LPS混养对应m2
        gear: brightness, // 档位直接使用brightness值
        R: rDuty, // R通道空占比
        G: gDuty, // G通道空占比
        B: bDuty, // B通道空占比
        W: wDuty, // W通道空占比
        LB: lbDuty, // 浅蓝通道空占比
        RB: rbDuty, // 宝蓝通道空占比
        P: pDuty, // 紫光通道空占比
        UV: uvDuty // 紫外通道空占比
      }
    } else {
      // 其他模式的处理逻辑
      // 获取模式名称，例如：modeIndex=1对应m1，以此类推
      const modeCode = `m${modeIndex}`

      // 构建其他模式的MQTT消息
      mqttMessage = {
        mode: modeCode, // 模式代码，例如m1, m2等
        gear: brightness, // 档位直接使用brightness值
        R: 0, // R通道空占比
        G: 0, // G通道空占比
        B: 0, // B通道空占比
        W: 0, // W通道空占比
        LB: 0, // 浅蓝通道空占比
        RB: 0, // 宝蓝通道空占比
        P: 0, // 紫光通道空占比
        UV: 0 // 紫外通道空占比
      }
    }

    const arr = []
    for (var key in mqttMessage) {
      if (key != "mode" && key != "gear") {
        arr.push({
          n: key,
          v: parseInt((mqttMessage[key] * 100) / 1024)
        })
      }
    }

    storageService.saveLastManualVal(this.data.did, arr)
    if (!this.data.isManualMode && modeIndex != 0) {
      return
    }
    // 统一发送MQTT消息到ESP32，避免重复发送
    console.log(`发送MQTT消息: ${JSON.stringify(mqttMessage)}`)
    if (!this.data.isGroup) {
      appInstance.sendMtMsg(this.data.device.topicSend, "chgValAll1", arr);
    } else {
      this.data.devices.forEach(device => {
        appInstance.sendMtMsg(device.topicSend, "chgValAll1", arr);
      })
    }
  },

  // 弹出层相关函数
  goToSchedule: function () {
    if (this.data.isManualMode) {
      return
    }
    this.setData({
      showTimerPopup: true
    });
  },

  // 处理长按行程设置按钮
  handleLongPress: function () {
    const $t = this;
    // 切换灯光模式：从手动到自动，或从自动到手动
    if (this.data.isManualMode) {
      // 切换到自动模式
      storageService.saveLightModeState(this.data.did, 'auto');
      // 更新UI状态
      this.setData({
        isManualMode: false
      });
      this.showToast('已切换为自动模式', 'success')
    } else {
      // 当前是自动模式，切换到手动模式
      this.data.switchType = 2
      wx.showLoading({
        title: 'Loading......',
        mask: true,
        success: function () {
          $t.sendSwitchChange()
        }
      });

    }
  },

  closePopup: function () {
    this.setData({
      showTimerPopup: false,
    })
  },

  // 关闭首次访问提示
  closeFirstVisitTip: function () {
    this.setData({
      showFirstVisitTip: false,
    })
  },

  // 添加空的定时任务
  addEmptyTimerTask: function () {
    const {
      timerTasks
    } = this.data

    if (timerTasks.length >= 7) {
      wx.showToast({
        title: '最多只能添加\n7个行程',
        icon: 'none',
        duration: 2000,
      })
      return
    }

    // 使用当前选中的模式作为默认模式
    const currentIndex = this.data.currentIndex

    // 构造正确的模式代码和显示名称
    const modeCode = `m${currentIndex}`;

    // 使用modeImages中的名称作为显示名称，确保有备用方案

    let displayMode = '';

    // 优先使用modeImages中的名称
    if (this.data.modeImages && this.data.modeImages[currentIndex] && this.data.modeImages[currentIndex].name) {
      displayMode = this.data.modeImages[currentIndex].name;
    }
    // 其次使用modeOptions
    else if (this.data.modeOptions && this.data.modeOptions[currentIndex]) {
      displayMode = this.data.modeOptions[currentIndex];
    }
    // 最后使用预定义的名称数组
    else {
      displayMode = this.data.modeOptions[currentIndex] || '未知模式';
    }

    const newTask = {
      time: '--:--',
      endTime: '--:--',
      mode: modeCode, // 使用正确的模式代码格式（如m0、m1等）
      displayMode: displayMode, // 用于显示的模式名称
      modeIndex: currentIndex,
      brightness: 100, // 定时任务亮度范围为0-100，默认值0
      fadeIn: 10, // 修改默认值为 10
      fadeOut: 10, // 修改默认值为 10
      enabled: false,
      editing: true, // 新添加的任务默认处于编辑状态
      error: false, // 错误状态标志，用于显示红色边框
      crossZeroMode: false, // 跨0点模式状态
    }

    console.log(`添加新行程任务：模式代码=${modeCode}, 显示名称=${displayMode}`);

    this.setData({
      timerTasks: [...timerTasks, newTask],
    })
  },

  // 显示删除确认弹窗
  deleteTimerTask: function (e) {
    const index = e.currentTarget.dataset.index;
    if (!this.data.isManualMode && this.data.timerTasks[index].enabled) {
      wx.showModal({
        title: '提示',
        content: '行程模式，当前行程启用状态下，无法删除。',
        showCancel: false,
      })
      return
    }

    this.setData({
      showDeleteConfirm: true,
      deleteTaskIndex: index
    });
  },

  // 确认删除任务
  confirmDelete: function () {
    const {
      timerTasks,
      deleteTaskIndex
    } = this.data
    if (deleteTaskIndex >= 0) {
      timerTasks.splice(deleteTaskIndex, 1)
      this.setData({
          timerTasks: [...timerTasks],
          showDeleteConfirm: false,
          deleteTaskIndex: -1,
        },
        () => {
          this.saveShortcutModeData() // Save after deleting
        }
      )
    }
  },

  // 取消删除
  cancelDelete: function () {
    this.setData({
      showDeleteConfirm: false,
      deleteTaskIndex: -1,
    })
  },

  // 切换任务编辑模式
  toggleEditMode: function (e) {
    const index = e.currentTarget.dataset.index;
    const updatedTasks = [...this.data.timerTasks];
    const currentlyEditing = updatedTasks[index].editing;

    // 如果当前正在编辑，则保存编辑结果
    if (currentlyEditing) {
      // 检查时间是否有效
      if (updatedTasks[index].time === '--:--' || updatedTasks[index].endTime === '--:--') {
        wx.showToast({
          title: '请设置有效时间',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      /* //启用状态下禁止编辑
      // 检查是否有时间冲突
      if (updatedTasks[index].enabled && this.checkTimeOverlap(index)) {
        this.setData({
          showTimeConflictConfirm: true,
          timeConflictMessage: '此行程与其他已启用的行程时间存在冲突，请调整时间。'
        });
        return;
      }
      */
    } else {
      if (!this.data.isManualMode && updatedTasks[index].enabled) {
        wx.showModal({
          title: '提示',
          content: '行程模式，当前行程启用状态下，无法编辑。',
          showCancel: false,
        })
        return
      }
    }


    // 切换编辑状态
    updatedTasks[index].editing = !currentlyEditing;

    this.setData({
      timerTasks: updatedTasks
    });

    // 如果切换到非编辑状态，保存数据
    if (currentlyEditing) {
      this.saveShortcutModeData();
    }
  },

  /**
   * 切换行程任务启用状态
   */
  toggleTaskEnabled: function (e) {
    const index = e.currentTarget.dataset.index;
    const entityId = this.data.did;
    const isGroup = this.data.isGroup;
    const deviceType = this.data.device.deviceType;

    const updatedTasks = [...this.data.timerTasks];
    const enabled = !updatedTasks[index].enabled;

    this.data.tmpIndex = index
    this.data.tmpEnabled = enabled

    if (enabled) {
      // 检查时间是否有效
      if (updatedTasks[index].time === '--:--' || updatedTasks[index].endTime === '--:--') {
        this.showToast('请先设置有效时间')
        // 恢复开关状态
        updatedTasks[index].enabled = false;
        this.setData({
          timerTasks: updatedTasks,
        });
        return;
      }
      // 启用任务时，检查是否有冲突
      if (lightCommonService.checkTimeOverlap(this.data.timerTasks, index)) {
        wx.showModal({
          title: '行程时间冲突',
          content: '此行程与其他已启用的行程时间存在冲突，请先调整时间。',
          showCancel: false,
        });

        // 恢复开关状态
        updatedTasks[index].enabled = false;
        this.setData({
          timerTasks: updatedTasks,
        });
        return;
      }
      // 检查高阶模式是否有启用的曲线
      if (lightCommonService.checkAdvancedEnabled(entityId, isGroup, deviceType)) {
        // 恢复开关状态
        updatedTasks[index].enabled = false;
        this.setData({
          timerTasks: updatedTasks,
        });
        return;
      }
      this.data.switchType = 3
      this.sendNewSchedule2Device(1)
    } else {
      // 检查是否还有其他启用的行程卡片
      const hasOtherEnabledTasks = updatedTasks.some((task, i) => i !== index && task.enabled);
      // 如果关闭卡片且没有其他启用的卡片，重置控制条
      if (!hasOtherEnabledTasks) {
        this.data.switchType = 5
        const $t = this
        wx.showLoading({
          title: 'Loading......',
          mask: true,
          success: function () {
            $t.sendSwitchChange()
          }
        });
      } else {
        this.data.switchType = 4
        this.sendNewSchedule2Device(1)
      }
    }
  },

  // 编辑任务开始时间
  onEditTimeChange: function (e) {
    const index = e.currentTarget.dataset.index;
    const timeValue = e.detail.value;

    const updatedTasks = [...this.data.timerTasks];
    updatedTasks[index].time = timeValue;

    // 检查是否有时间冲突
    if (updatedTasks[index].endTime !== '--:--') {
      // 当设置结束时间早于开始时间时（非跨0点）
      const startMinutes = lightCommonService.timeToMinutes(timeValue);
      const endMinutes = lightCommonService.timeToMinutes(updatedTasks[index].endTime);

      if (startMinutes > endMinutes && !updatedTasks[index].crossZeroMode) {
        // 提示用户可能需要启用跨0点
        this.setData({
          showCrossZeroConfirm: true,
          crossZeroTaskIndex: index,
          crossZeroNewTime: timeValue,
          crossZeroNewEndTime: updatedTasks[index].endTime
        });
        return;
      }
    }

    this.setData({
      timerTasks: updatedTasks
    });
  },



  // 根据模式和亮度计算RGBW值
  calculateRGBWValues: function (modeIndex, brightness) {
    let valArr = []
    if (modeIndex < modeNum) {
      valArr = shortcutModeService.getValsByIdx(modeIndex, brightness, this.data.device.deviceType)
    } else {
      valArr = playerModeService.getValsByIdx(this.data.did, modeIndex - modeNum, brightness)
    }

    return valArr
  },

  onEditEndTimeChange: function (e) {
    const index = e.currentTarget.dataset.index;
    const endTimeValue = e.detail.value;

    const updatedTasks = [...this.data.timerTasks];
    updatedTasks[index].endTime = endTimeValue;

    // 检查是否有时间冲突
    if (updatedTasks[index].time !== '--:--') {
      // 当设置结束时间早于开始时间时（非跨0点）
      const startMinutes = lightCommonService.timeToMinutes(updatedTasks[index].time);
      const endMinutes = lightCommonService.timeToMinutes(endTimeValue);

      if (startMinutes > endMinutes && !updatedTasks[index].crossZeroMode) {
        // 提示用户可能需要启用跨0点
        this.setData({
          showCrossZeroConfirm: true,
          crossZeroTaskIndex: index,
          crossZeroNewTime: updatedTasks[index].time,
          crossZeroNewEndTime: endTimeValue
        });
        return;
      }
      if (updatedTasks[index].crossZeroMode && startMinutes < endMinutes) {
        updatedTasks[index].crossZeroMode = false
      }
    }


    this.setData({
      timerTasks: updatedTasks
    });
  },

  // 切换任务的跨0点模式
  toggleCrossZeroMode: function (e) {
    //禁用手动切换跨0点，根据时间大小自动判断
  },

  // 检查时间段是否有交集

  // 验证时间设置
  validateTimeSettings: function (index) {
    const task = this.data.timerTasks[index]
    if (task.time === '--:--' || task.endTime === '--:--') {
      return true
    }

    // 将时间转换为分钟数进行比较
    const startMinutes = lightCommonService.timeToMinutes(task.time);
    const endMinutes = lightCommonService.timeToMinutes(task.endTime);
    // 获取缓亮和缓暗时长
    const fadeIn = task.fadeIn
    const fadeOut = task.fadeOut

    let flag = true
    if (startMinutes < endMinutes) {
      if (startMinutes + fadeIn >= endMinutes - fadeOut) {
        //timeConflictMessage="您设置的时长小于渐变总时长（缓亮+缓暗）！"
        flag = false
      }
    } else {
      if (startMinutes - fadeOut <= 0 || endMinutes + fadeIn >= 24 * 60) {
        flag = false
      }
    }
    if (!flag) {
      // 更新时间冲突提示信息
      this.setData({
        showTimeConflictConfirm: true,
        timeConflictMessage: '您设置的时长小于渐变总时长（缓亮+缓暗）！',
      })
    }

    return flag
  },


  // 确认时间冲突提醒
  confirmTimeConflict: function () {
    this.setData({
      showTimeConflictConfirm: false,
      timeConflictMessage: '', // 重置错误消息
    })
  },

  // 检查所有任务是否有错误
  hasAnyTaskError: function () {
    const {
      timerTasks
    } = this.data
    return timerTasks.some(task => task.error)
  },

  /**
   * 确认跨0点设置
   */
  confirmCrossZero: function () {
    const {
      crossZeroTaskIndex,
      crossZeroNewTime,
      crossZeroNewEndTime
    } = this.data;

    if (crossZeroTaskIndex === undefined || !crossZeroNewTime || !crossZeroNewEndTime) {
      console.error('confirmCrossZero: 缺少必要参数');
      this.setData({
        showCrossZeroConfirm: false
      });
      return;
    }

    // 更新任务时间并启用跨0点模式
    const updatedTasks = [...this.data.timerTasks];
    updatedTasks[crossZeroTaskIndex].time = crossZeroNewTime;
    updatedTasks[crossZeroTaskIndex].endTime = crossZeroNewEndTime;
    updatedTasks[crossZeroTaskIndex].crossZeroMode = true;

    this.setData({
      timerTasks: updatedTasks,
      showCrossZeroConfirm: false,
      crossZeroTaskIndex: undefined,
      crossZeroNewTime: '',
      crossZeroNewEndTime: ''
    });

    // 保存数据
    this.saveShortcutModeData();
  },

  /**
   * 取消跨0点设置
   */
  cancelCrossZero: function () {
    this.setData({
      showCrossZeroConfirm: false,
      crossZeroTaskIndex: undefined,
      crossZeroNewTime: '',
      crossZeroNewEndTime: ''
    });
  },

  // 编辑任务模式
  onEditModeChange: function (e) {
    const index = e.currentTarget.dataset.index
    const newModeIndex = parseInt(e.detail.value)
    const modeOptions = this.data.modeOptions
    const timerTasks = [...this.data.timerTasks]

    // 设置正确的模式名称和索引
    timerTasks[index].modeIndex = newModeIndex
    if (newModeIndex < modeNum) {
      timerTasks[index].mode = `m${newModeIndex}` // 使用m0, m1等格式
    } else {
      timerTasks[index].mode = `p${(newModeIndex-modeNum)}` // 使用m0, m1等格式
    }


    // 使用modeImages中的名称作为显示名称
    timerTasks[index].displayMode = modeOptions[newModeIndex]

    this.setData({
        timerTasks: [...timerTasks],
      },
      () => {
        // 重新验证任务
        //this.validateTimeSettings(index)
        this.saveShortcutModeData()
      }
    )
  },

  // 编辑任务缓亮时长
  onEditFadeInChange: function (e) {
    const index = e.currentTarget.dataset.index;
    let value = parseInt(e.detail.value);

    // 确保值为非负数
    if (isNaN(value) || value < 0) value = 0;

    const updatedTasks = [...this.data.timerTasks];
    updatedTasks[index].fadeIn = value;

    this.setData({
      timerTasks: updatedTasks
    });
  },

  // 编辑任务缓暗时长
  onEditFadeOutChange: function (e) {
    const index = e.currentTarget.dataset.index;
    let value = parseInt(e.detail.value);

    // 确保值为非负数
    if (isNaN(value) || value < 0) value = 0;

    const updatedTasks = [...this.data.timerTasks];
    updatedTasks[index].fadeOut = value;

    this.setData({
      timerTasks: updatedTasks
    });
  },

  onFadeInBlur: function (e) {
    const index = e.currentTarget.dataset.index;
    let value = parseInt(e.detail.value);

    // 确保值为非负数
    if (isNaN(value) || value < 0) value = 0;

    const updatedTasks = [...this.data.timerTasks];
    updatedTasks[index].fadeIn = value;

    this.setData({
      timerTasks: updatedTasks
    });
  },

  onFadeOutBlur: function (e) {
    const index = e.currentTarget.dataset.index;
    let value = parseInt(e.detail.value);

    // 确保值为非负数
    if (isNaN(value) || value < 0) value = 0;

    const updatedTasks = [...this.data.timerTasks];
    updatedTasks[index].fadeOut = value;

    this.setData({
      timerTasks: updatedTasks
    });
  },

  // 亮度调整处理函数，使用防抖版本
  handleBrightnessChange: function (e) {
    const index = this.data.currentIndex
    const brightness = e.detail.value

    // 更新UI
    const modeSettings = [...this.data.modeSettings]
    modeSettings[index].brightness = brightness

    // 更新当前选中模式的亮度设置
    this.batchUpdate({
      [`modeSettings[${index}].brightness`]: brightness,
    })

    // 使用防抖函数发送亮度更新命令
    this.debouncedSendBrightness(index, brightness)

    // 保存状态到存储
    this.saveShortcutModeData() // << Call helper
  },

  // 模式选择处理函数，使用节流版本
  selectMode: function (e) {
    const index = e.currentTarget.dataset.index
    if (index !== this.data.currentIndex) {
      this.throttledModeChange(index)
    }
  },

  handleModeChange: function (index) {
    // 防止索引越界
    if (index < 0 || index >= this.data.modeImages.length) {
      console.warn('handleModeChange: 无效的模式索引', index)
      return
    }

    this.setData({
      currentIndex: index,
    })

    // 更新图片样式
    this.updateImageClasses(index)

    // 发送亮度信号给设备
    const brightness = this.data.modeSettings[index].brightness
    this.sendBrightnessToDevice(index, brightness)

    // 保存当前模式索引和设置 - Call helper instead
    this.saveShortcutModeData()
  },

  // 保存快捷模式数据（包括当前索引、模式设置、定时任务）
  saveShortcutModeData: function () {
    const entityId = this.data.device.deviceId
    const isGroup = 0
    const deviceType = this.data.device.deviceType

    const dataToSave = {
      currentIndex: this.data.currentIndex,
      modeSettings: this.data.modeSettings,
      timerTasks: this.data.timerTasks, // << Include timerTasks
    }
    // **传递 deviceType**
    storageService.saveShortcutModeData(entityId, dataToSave, isGroup, deviceType) // << PASS deviceType
  },

  // 验证任务并保存，可选择是否立即发送
  validateAndSaveTasks: function (sendImmediately = true) {
    // 验证所有任务
    const {
      timerTasks
    } = this.data;
    let hasError = false;

    // 遍历任务进行验证
    timerTasks.forEach((task, index) => {
      if (task.time !== '--:--' && task.endTime !== '--:--') {
        this.validateTimeSettings(index);
        if (task.error) {
          hasError = true;
        }
      }
    });

    // 保存任务数据
    this.saveShortcutModeData();

    // 如果没有错误且需要立即发送，则发送MQTT消息
    if (!hasError && sendImmediately) {
      timerTasks.forEach((task, index) => {
        if (task.enabled) {
          this.sendTimerMqttMessage(index);
        }
      });
    }

    return !hasError;
  },

  /**
   * 亮度输入框获取焦点
   */
  onBrightnessFocus: function (e) {
    // 可以在这里添加亮度输入框获取焦点时的逻辑
  },

  onBrightnessBlur: function (e) {
    const index = e.currentTarget.dataset.index;
    let value = parseInt(e.detail.value);

    // 确保值为非负数
    if (isNaN(value) || value < 0) {
      value = 0
    }
    if (value > 100) {
      value = 100
    }

    const updatedTasks = [...this.data.timerTasks];
    updatedTasks[index].brightness = value;

    this.setData({
      timerTasks: updatedTasks
    });
  },

  onFadeInFocus: function (e) {},

  onFadeOutFocus: function (e) {},

  // 处理行程设置更新事件
  onTimerTasksUpdated: function (e) {
    const {
      timerTasks
    } = e.detail;
    if (Array.isArray(timerTasks)) {
      this.setData({
        timerTasks
      });
      console.log('行程设置已更新，任务数量:', timerTasks.length);
    }
  },

  // 关闭行程设置弹窗
  closePopup: function () {
    this.setData({
      showTimerPopup: false
    });
  },



  sendSwitchChange() {
    const $t = this
    if (!$t.data.isGroup) {
      appInstance.sendMtMsg($t.data.device.topicSend, "chgAutoRun", 0)
      $t.data.timeoutObj = setTimeout(function () {
        $t.switchChangeResult(0);
      }, 5000);
    } else {
      $t.data.syncNum = 0
      $t.data.devices.forEach(device => {
        appInstance.sendMtMsg(device.topicSend, "chgAutoRun", 0);
      })
      $t.data.timeoutObj = setTimeout(function () {
        $t.switchChangeResultGroup(0);
      }, 8000);
    }
  },
  switchChangeResult(succ) {
    //两种情况调用：2自动切手动、5最后一个启用的行程被禁用
    wx.hideLoading();
    if (succ == 0) {
      //最后一个启用的行程被禁用
      if (this.data.switchType == 5) {
        wx.showModal({
          title: '提示',
          content: '禁用异常，请求响应超时...',
          showCancel: false,
        })
      } else {
        wx.showModal({
          title: '提示',
          content: '切换模式异常，请求响应超时...',
          showCancel: false,
        })
      }
    } else {
      clearTimeout(this.data.timeoutObj);
      let entityId = this.data.did
      if (this.data.switchType == 2) {
        //禁用所有task
        const updatedTasks = [...this.data.timerTasks]
        updatedTasks.forEach(task => {
          task.enabled = false
        })
        this.setData({
          timerTasks: updatedTasks,
        })
        //禁用高阶模式
        advancedModeService.disableAdvancedCurves(entityId)
        storageService.saveLightModeState(entityId, 'manual');
        this.setData({
          isManualMode: true
        });
        this.showToast('已切换为手动模式', 'success')
        const index = this.data.currentIndex
        const brightness = this.data.modeSettings[index].brightness
        this.sendBrightnessToDevice(index, brightness)
      } else if (this.data.switchType == 5) { //最后一个启用的行程被禁用
        const updatedTasks = [...this.data.timerTasks]
        updatedTasks[this.data.tmpIndex].enabled = this.data.tmpEnabled
        this.setData({
          timerTasks: updatedTasks,
        })
        this.sendBrightnessToDevice(0, 0)
      }
      // 保存更新后的数据
      this.saveShortcutModeData()
      storageService.removeScheduleInfo(this.data.did)
      const pages = getCurrentPages()
      pages[0].changeStartEndTimeById(this.data.did, null)
    }
  },
  switchChangeResultGroup(succ) {
    if (succ == 1) {
      this.data.syncNum++
    }
    if (this.data.syncNum >= this.data.devices.length) {
      this.switchChangeResult(1)
      return
    }
    if (succ == 0) {
      if (this.data.syncNum == 0) {
        this.switchChangeResult(0)
      } else {
        wx.hideLoading()
        //最后一个启用的行程被禁用
        if (this.data.switchType == 5) {
          wx.showModal({
            title: '提示',
            content: '禁用异常，部分设备失败，请检查设备状态并重新操作。成功' + this.data.syncNum + '台，失败' + (this.data.devices.length - this.data.syncNum) + '台',
            showCancel: false,
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '切换模式异常，部分设备失败，请检查设备状态并重新操作。成功' + this.data.syncNum + '台，失败' + (this.data.devices.length - this.data.syncNum) + '台',
            showCancel: false,
          })
        }
      }
    }

  },

  sendNewSchedule2Device(needUpdate) {
    console.log(JSON.stringify(this.data.timerTasks))
    const updatedTasks = [...this.data.timerTasks]
    if (needUpdate == 1) {
      updatedTasks[this.data.tmpIndex].enabled = this.data.tmpEnabled
    }
    const newTasks = []
    for (var i = 0; i < updatedTasks.length; i++) {
      var curTimeTask = updatedTasks[i]
      if (!curTimeTask.enabled) {
        continue
      }
      // 当前任务时间
      const currentStartTime = lightCommonService.timeToMinutes(curTimeTask.time);
      const currentEndTime = lightCommonService.timeToMinutes(curTimeTask.endTime);
      console.log(`任务时间：${currentStartTime}-${currentEndTime}`)
      if (currentStartTime < currentEndTime) { //TODO保存时候校验时间是否合理end-start-fadeIn-fadeOut>0
        curTimeTask.tStart = currentStartTime
        curTimeTask.tEnd = currentEndTime
        newTasks.push(curTimeTask)
      } else {
        const newTask1 = JSON.parse(JSON.stringify(curTimeTask))
        newTask1.tStart = 0
        newTask1.tEnd = currentEndTime
        newTask1.eZero = 1
        newTasks.push(newTask1)
        const newTask2 = JSON.parse(JSON.stringify(curTimeTask))
        newTask2.tStart = currentStartTime
        newTask2.tEnd = 23 * 60 + 59
        newTask2.sZero = 1
        newTasks.push(newTask2)
      }
    }
    newTasks.sort((a, b) => a.time - b.time);
    console.log(newTasks)

    const tlsArr = []
    for (var j = 0; j < channelNum; j++) {
      tlsArr.push([])
    }
    for (var i = 0; i < newTasks.length; i++) {
      let tmin = newTasks[i].tStart % 60
      let thour = (newTasks[i].tStart - tmin) / 60
      let emin = newTasks[i].tEnd % 60
      let ehour = (newTasks[i].tEnd - emin) / 60
      let fadeIn = newTasks[i].fadeIn
      let fadeOut = newTasks[i].fadeOut
      if (fadeIn <= 0) {
        fadeIn = 1
      }
      if (fadeOut <= 0) {
        fadeOut = 1
      }
      let t_tmin = (newTasks[i].tStart + fadeIn) % 60
      let t_thour = (newTasks[i].tStart + fadeIn - t_tmin) / 60
      let t_emin = (newTasks[i].tEnd - fadeOut) % 60
      let t_ehour = (newTasks[i].tEnd - fadeOut - t_emin) / 60
      console.log(t_tmin + ":" + t_thour + ":" + t_emin + ":" + t_ehour)
      let valArr = this.calculateRGBWValues(newTasks[i].modeIndex, newTasks[i].brightness)

      for (var j = 0; j < channelNum; j++) {
        let arr = tlsArr[j]
        let val = valArr[j]
        if (newTasks[i].eZero && newTasks[i].eZero == 1) {
          arr.push([0, val])
        } else {
          arr.push([thour * 10000 + tmin * 100, 0])
          arr.push([t_thour * 10000 + t_tmin * 100, val])
        }
        if (newTasks[i].sZero && newTasks[i].sZero == 1) {
          arr.push([23 * 10000 + 59 * 100 + 59, val])
        } else {
          arr.push([t_ehour * 10000 + t_emin * 100, val])
          arr.push([ehour * 10000 + emin * 100, 0])
        }
      }
    }
    const mattData = {
      tls: [tlsArr],
      w: [0, 0, 0, 0, 0, 0, 0]
    }
    console.log(`发送行程模式MQTT消息: ${JSON.stringify(mattData)}`)

    const $t = this;
    wx.showLoading({
      title: 'Loading......',
      mask: true,
      success: function () {
        $t.data.mqttData = mattData;
        $t.sendSyncToDeviceDialog(mattData)
      }
    })
  },

  sendSyncToDeviceDialog(mattData) {
    const $t = this
    if (!$t.data.isGroup) {
      appInstance.sendMtMsg($t.data.device.topicSend, "syncDataUp", mattData)
      $t.data.timeoutObj = setTimeout(function () {
        $t.handleSyncToDeviceDialogResult(0);
      }, 5000);
    } else {
      $t.data.syncNum = 0
      $t.data.devices.forEach(device => {
        appInstance.sendMtMsg(device.topicSend, "syncDataUp", mattData);
      })
      $t.data.timeoutObj = setTimeout(function () {
        $t.handleSyncToDeviceDialogResultGroup(0);
      }, 8000);
    }
  },
  handleSyncToDeviceDialogResult(succ) {
    //两种情况下调用：3启用、4禁用
    wx.hideLoading();
    if (succ == 0) {
      wx.showModal({
        title: '提示',
        content: '启用/禁用异常，请求响应超时...',
        showCancel: false,
      })
      const updatedTasks = [...this.data.timerTasks]
      updatedTasks[this.data.tmpIndex].enabled = !this.data.tmpEnabled
      this.setData({
        timerTasks: updatedTasks,
      })
    } else {
      clearTimeout(this.data.timeoutObj);
      //3启用、4禁用
      const updatedTasks = [...this.data.timerTasks];
      updatedTasks[this.data.tmpIndex].enabled = this.data.tmpEnabled;
      this.setData({
        timerTasks: updatedTasks,
      });

      // 保存更新后的数据
      this.saveShortcutModeData()

      const pages = getCurrentPages()
      storageService.saveScheduleInfo(this.data.did, this.data.mqttData)
      pages[0].changeStartEndTimeById(this.data.did, this.data.mqttData)
      this.data.mqttData = null;
    }
  },
  handleSyncToDeviceDialogResultGroup(succ) {
    if (succ == 1) {
      this.data.syncNum++
    }
    if (this.data.syncNum >= this.data.devices.length) {
      this.handleSyncToDeviceDialogResult(1)
      return
    }
    if (succ == 0) {
      if (this.data.syncNum == 0) {
        this.handleSyncToDeviceDialogResult(0)
      } else {
        wx.hideLoading()
        wx.showModal({
          title: '提示',
          content: '启用/禁用异常，部分设备失败，请检查设备状态或重新同步，成功率' + (this.data.syncNum * 100 / this.data.devices.length).toFixed(2) + "%！",
          showCancel: false,
        })
        const updatedTasks = [...this.data.timerTasks]
        updatedTasks[this.data.tmpIndex].enabled = !this.data.tmpEnabled
        this.setData({
          timerTasks: updatedTasks,
        })
      }
    }

  },

  showToast(msg, icon = 'none', duration = 1500) {
    wx.showToast({
      title: msg,
      icon: icon,
      duration: duration
    })
  },

  // 页面卸载时保存数据
  onUnload: function () {
    this.saveShortcutModeData()
    const $t = this
    if (!this.data.isGroup) {
      wx.$event.remove(this.data.device.topicSub, this)
    } else {
      this.data.devices.forEach(device => {
        wx.$event.remove(device.topicSub, $t)
      })
    }
  },

})